import { Component, OnInit } from '@angular/core';
import { NzResizeEvent } from 'ng-zorro-antd/resizable';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import * as xlsx from 'xlsx';
@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit {

  constructor() { }
  width = 100;
  height = 100;

  cols = [
    {
      title: 'Name',
      width: '180px'
    },
    {
      title: 'Age',
      width: '180px'
    },
    {
      title: 'Address',
      width: '200px'
    },
    {
      title: 'Actions'
    }
  ];

  listOfData = [
    {
      key: '1',
      name: 'John Brown',
      age: 32,
      address: 'New York No. 1 Lake Park'
    },
    {
      key: '2',
      name: 'Jim Green',
      age: 42,
      address: 'London No. 1 Lake Park'
    },
    {
      key: '3',
      name: 'Joe Black',
      age: 32,
      address: 'Sidney No. 1 Lake Park'
    }
  ];
  movies = [
    'Episode I - The Phantom Menace',
    'Episode II - Attack of the Clones',
    'Episode III - Revenge of the Sith',
    'Episode IV - A New Hope',
    'Episode V - The Empire Strikes Back',
    'Episode VI - Return of the Jedi',
    'Episode VII - The Force Awakens',
    'Episode VIII - The Last Jedi',
    'Episode IX – The Rise of Skywalker'
  ];

  ngOnInit(): void {
  }
  onResize({ width }: NzResizeEvent, col: string): void {
    this.cols.some(e => { (e.title === col ? e.width = `${width}px` : e = e); });
  }
  onResizeEnd({ width, height }) {

  }
  onResizeStart(width, height) {

  }
  onResize1({ width, height }) {
    this.height = height;
    this.width = width;
  }

  drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.movies, event.previousIndex, event.currentIndex);
  }

  creatXlsx(): any {
    const matrix = [
      [1, 2, 3, 4],
      [1, 2, 3, 4],
      [1, 2, 3, 4],
      [1, 2, 3, 4]
    ];
    // 二维数组
    const ws = xlsx.utils.aoa_to_sheet(matrix);
    const ws2 = xlsx.utils.json_to_sheet([]) ;
    // table element
    const ws3 = xlsx.utils.table_to_sheet(document.createElement('table')) ;
    const [i, j , k] = [3, 5, 6] ;

    /* s是起始单元格，e是结束单元格 c0 r0 第一行第一列
      数据要放在合并的单元格的第一个 不然会消失
    */
    ws['!merges'] = [
      { s: {c: 0, r: 0},
        e: {c: 0, r: 1} },
        { s: {c: 1, r: 0},
        e: {c: 1, r: 1} },
        { s: {c: 2, r: 0},
        e: {c: 1 + i , r: 0} },
        { s: {c: 2 + i , r: 0},
        e: {c: 1 + i  + j, r: 0} },
        { s: {c: 2 + i  + j , r: 0},
        e: {c:  k - 2, r: 0} },
       ]as xlsx.Range[] ;
    const data = xlsx.utils.book_new();
    xlsx.utils.book_append_sheet(data, ws, 'Sheet1');
    xlsx.writeFile(data, 'text1', {});
  }


  paste(e){
    console.log(e);
  }
}

function sheet2blob(sheet, sheetName) {// 将文件转换为二进制文件
  sheetName = sheetName || 'sheet1';
  const workbook = {
    SheetNames: [sheetName],
    Sheets: {}
  };
  workbook.Sheets[sheetName] = sheet;
  // 生成excel的配置项
  const wopts: xlsx.WritingOptions = {
    bookType: 'xlsx', // 要生成的文件类型
    bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
    type: 'binary'
  };
  const wbout = xlsx.write(workbook, wopts);
  const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });
  // 字符串转ArrayBuffer
  function s2ab(s) {
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);
    for (let i = 0; i !== s.length; ++i) { view[i] = s.charCodeAt(i) & 0xFF; }
    return buf;
  }
  return blob;
}

function downLoadExcel(data, fileName) {
  // 定义表头
  let str = `用户名,时间,坐标,来源,授权时间\n`;
  // 增加\t为了不让表格显示科学计数法或者其他格式
  for (let i = 0; i < data.length; i++) {
    for (const item in data[i]) {
      str += `${data[i][item] + '\t'},`;
    }
    str += '\n';
  }
  // encodeURIComponent解决中文乱码
  const uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
  // 通过创建a标签实现
  const link = document.createElement('a');
  link.href = uri;
  // 对下载的文件命名
  link.download = `${fileName || '表格数据'}.csv`;
  link.click();
}

const xlsxUtil = {
  fileData: {}, // 导出的二进制对象
  // data格式   [["A1数据","B1数据","C1数据"],["A2数据","B2数据","C2数据"]...]
  buildExcelDate(data) {
    const excelData = {};
    data.forEach(function(value, i) {
      i += 1;
      value.forEach(function(value01, j) {
        excelData[xlsxUtil.createCellPos(j) + i] = { v: value01 };
      });
    });
    return excelData;
  },
  // 生成excel  type为下载文件后缀  json对象格式｛A1:{v:"数据"}，B1:{..}..｝
  buildExcel(json, type) {
    if (typeof Object.assign != 'function') {
      Object.assign = function(target) {
        'use strict';
        if (target == null) {
          throw new TypeError('Cannot convert undefined or null to object');
        }

        target = Object(target);
        for (let index = 1; index < arguments.length; index++) {
          const source = arguments[index];
          if (source != null) {
            for (const key in source) {
              if (Object.prototype.hasOwnProperty.call(source, key)) {
                target[key] = source[key];
              }
            }
          }
        }
        return target;
      };
    }

    json = xlsxUtil.buildExcelDate(json);
    const outputPos = Object.keys(json);
    const fileJson = {
      SheetNames: ['mySheet'], // 保存的表标题
      Sheets: {
        mySheet: Object.assign(
          json, // 内容
          {
            '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] // 设置填充区域
          })
      }
    };
    console.log(fileJson);
    // 创建二进制对象写入转换好的字节流
    const fileData = new Blob([xlsxUtil.s2ab(xlsx.write(fileJson,
      { bookType: (type == undefined ? 'xlsx' : type), bookSST: false, type: 'binary' }// 这里的数据是用来定义导出的格式类型
    ))], {
      type: ''
    });
    return fileData;
  },
  isIE() { // ie?
    if (!!window['ActiveXObject'] || 'ActiveXObject' in window) {
      return true;
    }
    else {
      return false;
    }
  },
  s2ab(s) { // 字符串转字符流
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);
    for (let i = 0; i != s.length; ++i) { view[i] = s.charCodeAt(i) & 0xFF; }
    return buf;
  },
  // 数字转excel列，  0-A
  createCellPos(n) {
    const ordA = 'A'.charCodeAt(0);
    const ordZ = 'Z'.charCodeAt(0);
    const len = ordZ - ordA + 1;
    let s = '';
    while (n >= 0) {
      s = String.fromCharCode(n % len + ordA) + s;
      n = Math.floor(n / len) - 1;
    }
    return s;
  },
  // 模拟下载 a标签id，下载文件名称，Blob
  downloadExcel(aId, fileName, blob) {
    let save_link = document.createElement('a');
    save_link.href = URL.createObjectURL(blob); // 创建对象超链接
    save_link.download = fileName + '.xlsx';
    save_link.click(); // 模拟下载
    URL.revokeObjectURL(blob); // 释放这个object URL}

  },
  // 生成和模拟下载
  buildAndDownload(aId, fileName, json, type) {
    const blob = xlsxUtil.buildExcel(json, type);
    if (xlsxUtil.isIE()) {
      // window.navigator.msSaveOrOpenBlob(blob,fileName+".xlsx");

    } else {
      xlsxUtil.downloadExcel(aId, fileName, blob);
    }
  }

};
